package com.ia2014.tp.portal2.servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ia2014.tp.portal2.facades.FacadeVenta;
import com.ia2014.tp.portal2.vo.UsuarioVO;

/**
 * Servlet para autenticar al usuario
 * @author Diego Alejandro
 *
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	
	@EJB
	private FacadeVenta facacade;
	
	public LoginServlet(){
		super();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.process(req, resp);
	}

	private void process(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException{
		
		String user = req.getParameter("usuario");
		String password = req.getParameter("password");
		String redirect = "portal";
	
			if (user == null || user.isEmpty() || password == null || password.isEmpty()){
				redirect = "login.jsp?error=1";
			}
			
			else{
				UsuarioVO usuarioVO = new UsuarioVO();
				usuarioVO.setUserLogin(user);
				usuarioVO.setPassword(password);
				
				if (this.facacade.login(usuarioVO)){
					HttpSession sesion = req.getSession(true);
					sesion.setAttribute("usuarioVO", usuarioVO);
				}
				else{
					redirect = "login.jsp?error=2";
				}
			}
		
		resp.sendRedirect(redirect);
	}	
}
